<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolBar" style="float:left;padding-top: 10px;padding-left: 50px;">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-form-item prop="tradeMonthRange">
          <el-date-picker
            style="width: 20em"
            v-model="filters.tradeMonthRange"
            type="monthrange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="yyyy-MM"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-search"
                     :label="$t('action.search')"
                     perms="finance:revenue:company"
                     @click="findPage"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-refresh"
                     :label="$t('action.reset')"
                     perms="finance:revenue:company"
                     @click="reset"/>
        </el-form-item>
      </el-form>
    </div>
    <!--表格内容栏-->
    <kt-table :data="pageResult" :columns="filterColumns" :exec-summary="true" @findPage="findPage"></kt-table>

    <!--说明-->
    <div class="toolBar" style="padding-top: 35px">
      <p align="left"><b>纯利润：</b>毛收入 - 退款费用 - 平台支出 - 固定成本 - 采购成本 - 包装成本</p>
      <p align="left"><b>总收入：</b>对当月销售订单的product_sales列进行汇总的金额</p>
      <p align="left"><b>毛收入：</b>对当月销售订单的total列进行汇总的金额，该项已经抵扣佣金、配送费、各种税费等</p>
      <p align="left"><b>退款费用：</b>对当月退款订单的total列汇总的金额，该项已经抵扣佣金、配送费等各项费用，是卖家承担退款的净损失金额</p>
      <p align="left"><b>平台支出：</b>对店铺营收页面的相关项目汇总，包括: 广告费用+促销活动+优惠券手续费+店铺租金+仓储物流+债务费用+早期评论人+物流库存报销+物流赔偿收入调整+入库配置费+AWD仓储费</p>
      <p align="left"><b>固定成本：</b>对固定成本页面的相关项目汇总，包括: 美工费用+样品费用+耗材费用+人工费用+租金水电+财务记账+头程付款+其他费用</p>
      <p align="left"><b>预估头程：</b>(销售数量 - 退款数量) * SKU管理配置的头程单价</p>
      <p align="left"><b>实际头程：</b>来源于固定成本页面录入的头程费用（包括Send费用）</p>
      <p align="left"><b>采购成本：</b>(销售数量 - 退款数量) * 产品管理配置的采购单价</p>
      <p align="left"><b>包装成本：</b>(销售数量 - 退款数量) * 产品管理配置的包装单价</p>
    </div>
  </div>
</template>

<script>
  import KtTable from '../core/KtTable'
  import KtButton from '../core/KtButton'
  import TableColumnFilterDialog from '../core/TableColumnFilterDialog'

  export default {
    name: "Company",
    components: {
      KtTable,
      KtButton,
      TableColumnFilterDialog
    },
    data() {
      return {
        size: 'small',
        filters: {
          tradeMonthRange: [],
        },
        //初始表格列显示字段
        columns: [],
        //列显示过滤字段
        filterColumns: [],
        pageRequest: {pageNum: 1, pageSize: 10},
        pageResult: {},
        dialogVisible: false,
        editLoading: false,
        //编辑页面
        dataForm: {
          shop: '',
          tradeMonth: '',
          exchangeRate: 6.40
        },
        dataFormRules: {
          shop: [
            {required: true, message: '请选择店铺', trigger: 'blur'}
          ],
          tradeMonth: [
            {required: true, message: '请选择核算的月份', trigger: 'blur'}
          ]
        },
        //店铺
        shops: [],
        pickerOptions: {
          shortcuts: [{
            text: '本月',
            onClick(picker) {
              picker.$emit('pick', [new Date(), new Date()]);
            }
          }, {
            text: '上个月',
            onClick(picker) {
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit('pick', [start, start]);
            }
          }, {
            text: '今年至今',
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 3);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近六个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
      }
    },
    methods: {
      // 处理表格列过滤显示
      initColumns() {
        this.columns = [
          {prop: "tradeMonth", label: "月份", minWidth: 120},
          {prop: "netProfit", label: "纯利润(￥)", minWidth: 120, formatter: true},
          {prop: "productSales", label: "总收入(￥)", minWidth: 120, formatter: true},
          {prop: "saleRevenue", label: "毛收入(￥)", minWidth: 120, formatter: true},
          {prop: "returnFee", label: "退款费用(￥)", minWidth: 120, formatter: true},
          {prop: "platformSpendFee", label: "平台支出(￥)", minWidth: 120, formatter: true},
          {prop: "fixedCost", label: "固定成本(￥)", minWidth: 120, formatter: true},
          {prop: "purchaseFee", label: "采购成本(￥)", minWidth: 120, formatter: true},
          {prop: "packFee", label: "包装成本(￥)", minWidth: 120, formatter: true},
          {prop: "estimateHeadwayFee", label: "预估头程(￥)", minWidth: 120, formatter: true},
          {prop: "actualHeadwayFee", label: "实际头程(￥)", minWidth: 120, formatter: true},
        ];
        this.filterColumns = JSON.parse(JSON.stringify(this.columns));
      },
      //获取分页数据
      findPage(data) {
        if ((data !== null && typeof data !== 'undefined') && typeof data.pageRequest !== 'undefined') {
          this.pageRequest = data.pageRequest;
        }
        if (this.filters.tradeMonthRange === null) {
          this.filters.tradeMonthRange = [];
        }
        this.pageRequest.params = {
          fromTradeMonth: this.filters.tradeMonthRange.length >= 1 ? this.filters.tradeMonthRange[0] : '',
          toTradeMonth: this.filters.tradeMonthRange.length === 2 ? this.filters.tradeMonthRange[1] : '',
        };
        this.$api.revenue.companyFindPage(this.pageRequest).then((res) => {
          if (res.code === 200) {
            this.pageResult = res.data;
          }
        }).then((data !== null && typeof data !== 'undefined') ? data.callback : '');
      },
      //提交表单
      submitForm() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            let text = [
              '确认执行以下统计吗?',
              '店铺：' + this.dataForm.shop,
              '月份：' + this.dataForm.tradeMonth,
              '汇率：' + this.dataForm.exchangeRate
            ];
            let newDatas = [];
            let h = this.$createElement;
            for (let i in  text) {
              newDatas.push(h('p', null, text[i]));
            }
            this.$confirm(
              '提示',
              {
                title: '提示',
                message: h('div', null, newDatas),
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              this.editLoading = true;
              this.$api.revenue.execute(this.dataForm).then((res) => {
                if (res.code === 200) {
                  this.$message({message: res.data, type: 'success'});
                  this.dialogVisible = false;
                  this.$refs['dataForm'].resetFields();
                } else {
                  this.$message({message: res.message, type: 'error'});
                }
                this.editLoading = false;
                this.findPage();
              });
            })
          }
        })
      },
      //重置搜索条件
      reset() {
        this.$refs['filters'].resetFields();
        this.findPage();
      },
      //获取店铺信息
      findShops() {
        this.shops = localStorage.getItem('authorizedShops').split(',');
      }
    },
    mounted() {
      this.initColumns();
      this.findShops();
    }
  }
</script>

<style scoped>

</style>
